﻿using MediatR;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Supplieries
{
    /// <summary>
    /// 删除供应商
    /// </summary>
    public class DeleteSupplierHandler : IRequestHandler<DeleteSupplierCommand, Result>
    {
        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IBaseRepository<Suppliers> _supplierRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeleteSupplierHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplierRepository"></param>
        /// <param name="logger"></param>
        public DeleteSupplierHandler(IBaseRepository<Suppliers> supplierRepository,
                                     ILogger<DeleteSupplierHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _logger = logger;
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeleteSupplierCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                //查询数据
                var query = await (await _supplierRepository.GetAll()).Where(s => s.SupplierId == request.SupplierId).FirstAsync();
                if (query != null)
                {
                    //将未删除修改为已删除
                    query.IsSupplier = 2;
                }
                //修改数据
                var res = await _supplierRepository.Update(query);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "删除供应商成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "删除供应商异常" + ex.Message;
                _logger.LogError("删除供应商异常" + ex.Message);
            }
            return result;
        }
    }
}
